package com.huawei.rbac.latch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch
 * <p>
 * ：有countDown方法和await方法，CountDownLatch在初始化时，需要指定用给定一个整数作为计数器。
 * 当调用countDown方法时，计数器会被减1；当调用await方法时，如果计数器大于0时，
 * 线程会被阻塞，一直到计数器被countDown方法减到0时，线程才会继续执行。
 * 计数器是无法重置的，当计数器被减到0时，调用await方法都会直接返回
 */
public class CountDownLatchTester {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        List<Thread> threads = new ArrayList<>(3);
        threads.add(new Thread(new Customer(latch, "张三")));
        threads.add(new Thread(new Customer(latch, "李四")));
        threads.add(new Thread(new Customer(latch, "王五")));
        for (Thread thread : threads) {
            thread.start();
        }

        Thread.sleep(100);
        new Thread(new Waitress(latch, "♥小芳♥")).start();

        for (Thread thread : threads) {
            thread.join();
        }
    }
}
